/**
 * Project: onlycust
 * File created at 2021/12/15 7:24 下午
 * Copyright (c) 2018 linklogis.com all rights reserved.
 */
package com.taotao.frame.util;


import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatorUtils {

    /**
     * 手机号验证
     *
     * @param phone
     * @return 验证通过返回true
     */
    public static boolean isMobile(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    /**
     * 营业执照 统一社会信用代码（15位）
     *
     * @param license
     * @return
     */
    public static boolean isLicense15(String license) {
        if (StringUtils.isEmpty(license)) {
            return false;
        }
        if (license.length() != 15) {
            return false;
        }

        String businesslicensePrex14 = license.substring(0, 14);
        // 获取营业执照注册号前14位数字用来计算校验码
        String businesslicense15 = license.substring(14, license.length());
        // 获取营业执照号的校验码
        char[] chars = businesslicensePrex14.toCharArray();
        int[] ints = new int[chars.length];
        for (int i = 0; i < chars.length; i++) {
            ints[i] = Integer.parseInt(String.valueOf(chars[i]));
        }
        getCheckCode(ints);
        if (businesslicense15.equals(getCheckCode(ints) + "")) {
            // 比较 填写的营业执照注册号的校验码和计算的校验码是否一致
            return true;
        }
        return false;
    }

    /**
     * 获取 营业执照注册号的校验码
     *
     * @param ints
     * @return
     */
    private static int getCheckCode(int[] ints) {
        if (null != ints && ints.length > 1) {
            int ti = 0;
            int si = 0;
            // pi|11+ti
            int cj = 0;
            // （si||10==0？10：si||10）*2
            int pj = 10;
            // pj=cj|11==0?10:cj|11
            for (int i = 0; i < ints.length; i++) {
                ti = ints[i];
                pj = (cj % 11) == 0 ? 10 : (cj % 11);
                si = pj + ti;
                cj = (0 == si % 10 ? 10 : si % 10) * 2;
                if (i == ints.length - 1) {
                    pj = (cj % 11) == 0 ? 10 : (cj % 11);
                    return pj == 1 ? 1 : 11 - pj;
                }
            }
        }
        // end if
        return -1;
    }

    /**
     * 营业执照 统一社会信用代码（18位）
     *
     * @param license
     * @return
     */
    public static boolean isLicense18(String license) {
        if (StringUtils.isEmpty(license)) {
            return false;
        }
        if (license.length() != 18) {
            return false;
        }

        String regex = "^([159Y]{1})([1239]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-90-9ABCDEFGHJKLMNPQRTUWXY])$";
        if (!license.matches(regex)) {
            return false;
        }
        String str = "0123456789ABCDEFGHJKLMNPQRTUWXY";
        int[] ws = {1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28};
        String[] codes = new String[2];
        codes[0] = license.substring(0, license.length() - 1);
        codes[1] = license.substring(license.length() - 1, license.length());
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += str.indexOf(codes[0].charAt(i)) * ws[i];
        }
        int c18 = 31 - (sum % 31);
        if (c18 == 31) {
            c18 = 'Y';
        } else if (c18 == 30) {
            c18 = '0';
        }
        if (str.charAt(c18) != codes[1].charAt(0)) {
            return false;
        }
        return true;
    }

    public static boolean isValidEmail(String email) {
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }
        return false;
    }

    public static String encryPhone(String phone) {
        /**
         * 隐藏电话号码中间四位
         * 第一种写法，String.replaceAll()方法
         * $1表示正则表达式 (\d{3})\d*([0-9a-zA-Z]{4}) 的第一个括号内的表达式匹配到的内容，
         * 在本例中，$1表示182，$2表示6293，故最终结果为$1****$2，即182****6293
         */
        phone = phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2");
        System.out.println("phone的结果为：" + phone);
        return phone;
    }

    public static String encryIdCard(String idCard) {
        /**
         * 隐藏身份证中间四位
         * 第二种写法，Matcher.replaceAll方法
         * String.replaceAll()的内部实现就是Pattern.compile(regex).matcher(this).replaceAll(replacement)
         */
        String regex = "(\\d{6})\\d*([0-9a-zA-Z]{4})";
        Pattern credentialsPattern = Pattern.compile(regex);
        Matcher credentialsMatch = credentialsPattern.matcher(idCard);
        idCard = credentialsMatch.replaceAll("$1********$2");
        System.out.println("idCard的结果为：" + idCard);
        return idCard;
    }

    public static String encryName(String name) {
        if (StringUtils.isEmpty(name) || name.length() == 1) {
            return name;
        }
        if (name.length() == 2) {
            name = name.replaceFirst(name.substring(1), "*");
        } else {
            name = name.replaceFirst(name.substring(1, name.length() - 1), "*");
        }
        return name;
    }

    public static String encryCustName(String name) {
        if (StringUtils.isEmpty(name) || name.length() <= 3) {
            return name;
        } else {
            name = name.replaceAll(name.substring(1, name.length() - 2), "*");
        }
        return name;
    }


    public static String encryStringSub(String name, int start, int end) {
        if (StringUtils.isEmpty(name) || name.length() < start || name.length() < end) {
            return name;
        }
        System.out.println("name的开始为：" + name);
        char[] nameChars = name.toCharArray();
        for (int i = start; i < end; i++) {
            nameChars[i] = '*';
        }
        String res = String.valueOf(nameChars);
        System.out.println("res的结束为：" + res);
        return res;
    }


    /**
     * 校验对象所有字段是否合规
     *
     * @param obj
     * @param <T>
     */
    public static <T> void validateObj(T obj) {
        validateObj(obj, Default.class);
    }


    /**
     * 校验对象所有字段是否合规
     *
     * @param obj
     * @param groups
     * @param <T>
     */
    public static <T> void validateObj(T obj, Class<?>... groups) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validateSet = validator.validate(obj, groups);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                throw new IllegalArgumentException(constraintViolation.getMessage());
            }
        }
    }


    /**
     * 校验某个字段
     *
     * @param object
     * @param propertyName
     * @param <T>
     */
    public static <T> void validateProperty(T object, String propertyName) {
        validateProperty(object, propertyName, Default.class);
    }


    /**
     * 校验某个字段
     *
     * @param object
     * @param propertyName
     * @param groups
     * @param <T>
     */
    public static <T> void validateProperty(T object,
                                            String propertyName,
                                            Class<?>... groups) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validateSet = validator.validateProperty(object, propertyName, groups);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                throw new IllegalArgumentException(constraintViolation.getMessage());
            }
        }
    }


    public static void main(String[] args) {
        String sss = "13279856559";
        String idCard = "360120199902022010";
        System.out.println(encryStringSub(sss, 3, 6));
        System.out.println(encryStringSub(idCard, 6, 13));
    }

}
